package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.service.ISMSService;
import cn.wolfcode.wolf2w.business.util.RegexUtils;
import cn.wolfcode.wolf2w.business.util.SMSUtil;
import cn.wolfcode.wolf2w.common.core.exception.ServiceException;
import cn.wolfcode.wolf2w.common.core.utils.StringUtils;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 浪兎兎
 * @since 2025-05-29-13:56
 */
@Service
@Slf4j
public class SMSServiceImpl implements ISMSService {
    @Autowired
    private RedisService redisService;
    /**
     * 发送验证码
     * @param phone 发送的手机号
     */
    @Override
    public void sendMessage(String phone) {
        // 校验参数合法性
        if (StringUtils.isBlank(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        if (!RegexUtils.isPhoneLegal(phone)) {
            throw new ServiceException("手机号格式错误");
        }
        // 随机验证码
        Random random = new Random();
        int rand = random.nextInt(899999) + 100000;
        log.info("后台向手机号为 {} 的用户发送验证码：\u001B[92m{}\u001B[0m", phone, rand);
//        SMSUtil.sendAliyunMessage(phone, Integer.toString(rand)); // 暂时先不需要这个
        // 验证码存储到 redis
        redisService.setCacheObject(RedisKeys.CODE.join(phone), rand, RedisKeys.CODE.getTtl(), TimeUnit.SECONDS);
    }
}
